package com.prj.ufdm.core.util;

import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

public class UfdmX509TrustManager implements X509TrustManager {

	X509TrustManager sunJSSEX509TrustManager;
	
	UfdmX509TrustManager() throws Exception { 
		
        KeyStore keyStore = KeyStore.getInstance("JKS"); 
        
        keyStore.load(new FileInputStream("D:\\key\\tr_server.jks"), "tr8888".toCharArray());
        
        //keyStore.load(new FileInputStream("D:\\key\\tr_server_trust.jks"), "tr8888".toCharArray());
        
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509", "SunJSSE"); 
        
        trustManagerFactory.init(keyStore); 
        
        TrustManager arrTrustManager [] = trustManagerFactory.getTrustManagers(); 

        for (int i = 0; i < arrTrustManager.length; i++) { 
        	
        	System.out.println("\n \n  arrTrustManager["+i+"]:"+arrTrustManager[i]);
        	
        	X509Certificate[] x509Cert = ((X509TrustManager) arrTrustManager[i]).getAcceptedIssuers();
        	for(int j=0;j<x509Cert.length;j++){
        		System.out.println("\n x509Cert["+i+"]["+j+"]:"+ x509Cert[j].getSubjectDN());
        	}
        	
        	
            if (arrTrustManager[i] instanceof X509TrustManager) { 
                sunJSSEX509TrustManager = (X509TrustManager) arrTrustManager[i]; 
                return;
            } 
        } 
        
    }
	
	@Override
	public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		sunJSSEX509TrustManager.checkClientTrusted(chain, authType); 
	}

	@Override
	public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		sunJSSEX509TrustManager.checkServerTrusted(chain, authType); 
	}

	@Override
	public X509Certificate[] getAcceptedIssuers() {
//		return new X509Certificate[] {};
		return sunJSSEX509TrustManager.getAcceptedIssuers(); 
	}

}
